package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.service.WebSocketServer;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public Result submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.判断收件地址是否为空
        AddressBook addressBookById = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBookById == null){
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.判断购物车是否为空
        //拿到用户id
        Long userId = BaseContext.getCurrentId();
        //拿到购物车集合
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.showShoppingCar(userId);
        //判断购物车是否为空,是则返回报错信息
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //3.插入订单表(order)
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        //支付状态 0未支付 1已支付 2退款
        orders.setStatus(orders.UN_PAID);
        //用户名(user)
        //下单用户id
        orders.setUserId(BaseContext.getCurrentId());
        //创建地址簿对象
        AddressBook addressBook = new AddressBook();
        //手机号(addressBook)
        orders.setPhone(addressBook.getPhone());
        //地址(addressBook)
        orders.setAddress(addressBook.getDetail());
        //收获人(addressBook)
        orders.setConsignee(addressBook.getConsignee());
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //插入订单表
        orderMapper.addOrder(orders);

        //4.批量插入订单明细表
        //创建集合接收数据
        List<OrderDetail> orderDetailList = new ArrayList();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            //把购物车数据复制给对象
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //插入缺少的数据orderId
            orderDetail.setOrderId(orders.getId());
            //明细表把对象插入集合
            orderDetailList.add(orderDetail);
        }
        //把集合传入数据库
        orderDetailMapper.addOrderDetail(orderDetailList);
        //5.清空购物车数据(根据用户id)
        shoppingCartMapper.clean(userId);

        //6.封装数据并返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());

        return Result.success(orderSubmitVO);
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo){
        //当前登录用户id
        Long userId = BaseContext.getCurrentId();

        //根据订单号查询当前用户的订单
        Orders orders = orderMapper.getByNumberAndUserId(outTradeNo,userId);

        //根据订单号id更新订单的状态、支付方式、支付状态、结账时间
        Orders build = Orders.builder()
                .id(orders.getId())
                .status(Orders.TO_BE_CONFIRMED) //待接单
                .payStatus(Orders.PAID) //已支付
                .checkoutTime(LocalDateTime.now()) //订单完成时间
                .build();

        orderMapper.update(build);

        Map map = new HashMap();
        map.put("type",1); //消息类型,1表示来单提醒
        map.put("orderId",build.getId());
        map.put("content","订单号:"+outTradeNo);

        //通过WebSocket实现来单提醒,向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户催单
     *
     * @param id
     * @return
     */
    @Override
    public Result reminder(Long id) {
        //1.非空校验查询用户订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //2.使用WebSocket催单
        Map map = new HashMap();
        map.put("type",2); //2表示催单
        map.put("orderId",id); //id
        map.put("content",orders.getNumber()); //设置订单号
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        //4.返回数据
        return Result.success();
    }

    /**
     * 历史订单查询
     *
     * @param pageNum
     * @param pageSize
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @Override
    public PageResult pageQueryUser(int pageNum, int pageSize, Integer status) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //创建Vo集合
        List<OrderVO> orderVOList = new ArrayList();

        //查询订单明细,并封装进OrderVO进行响应
        if ( page != null && page.getTotal() > 0){
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                orderVOList.add(orderVO);
            }
        }



        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 查询订单详细
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public Result cancel(Long id) {
        //1.根据id创建对象
        Orders orders = orderMapper.getById(id);

        //2.非空校验
        if (orders == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //若订单状态大于2,则表示已接单,不能取消
        if(orders.getStatus() > 2){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //根据id创建新对象
        Orders newOrders = new Orders();
        newOrders.setId(orders.getId());

        //订单状态处于待接单的需要进行退款
//        if (newOrders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
//            //支付状态修改为 退款
//            newOrders.setPayStatus(Orders.REFUND);
//        }

        // 把查询到的订单状态改为取消
        // 更新订单状态、取消原因、取消时间
        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setCancelReason("用户取消");
        newOrders.setCancelTime(LocalDateTime.now());
        orderMapper.update(newOrders);

        //4.返回数据
        return Result.success();
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public Result again(Long id) {
        //1.查询当前用户id
        Long userId = BaseContext.getCurrentId();
        //2.根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //3.根据订单详情转换成购物车对象
        orderDetailList.stream().map(x->{
            ShoppingCart shoppingCart = new ShoppingCart();
            //4.将订单详情里的菜单信息再次添加进购物车的内,再次下单
            BeanUtils.copyProperties(x,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //5.将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(orderDetailList);
        //6.返回数据
        return Result.success();
    }


    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult Search(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1.非空校验,并设置页面
        if (ordersPageQueryDTO.getPage() == null){
            ordersPageQueryDTO.setPage(1);
        }
        if (ordersPageQueryDTO.getPageSize() == null){
            ordersPageQueryDTO.setPageSize(5);
        }

        //2.开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //3.条件分页查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //4.部分订单状态,需要额外退回订单菜品信息,将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(),orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page){
        //返回订单菜品信息,自定义OrderVO响应结果
        List<OrderVO> ordersVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)){
            for (Orders orders : ordersList) {
                //将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                String orderDishes = getOrderDishesStr(orders);

                //将订单菜品信息封装到OrderVO中,并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                ordersVOList.add(orderVO);
            }
        }
        return ordersVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders){
        //查询订单菜品详情信息(订单中的菜品和数量)
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        //将每一条订单菜品信息拼接为字符串
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        //将该订单对应的所有菜品信息拼接在一起
        return String.join("",orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        //待接单
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //待派送
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        //派送中的订单数量
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待接单数量
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        //待派送数量
        orderStatisticsVO.setConfirmed(confirmed);
        //派送中数量
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public Result confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //非空校验
        if (ordersConfirmDTO == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //创建order对象,传入id以及状态
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        //修改状态为下单
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public Result rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
        }

//        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);

        return Result.success();
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public Result orderCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //设置支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

        return Result.success();
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public Result delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public Result complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
        return Result.success();
    }
}
